﻿CREATE PROCEDURE [dbo].[Clientes_DevolverPorId]

@IdCliente INT

AS

SELECT c.IdCliente,
	c.IdRubroCliente,
	c.IdTipoIva,
	c.IdListaPrecioVenta,
	c.IdVendedor,
	c.IdTipoMensajeriaInstantanea,
	c.Codigo,
	c.Nombre,
	c.Email,
	c.SitioWeb,
	c.DescuentoRecargo,
	c.LimiteDeuda,
	c.Cuit,
	c.EstaEliminado,
	c.MensajeriaInstantanea,
	CAST((CASE WHEN (SELECT COUNT(dc.IdDomicilioCliente) 
					FROM DomiciliosClientes dc
					WHERE dc.IdCliente = c.IdCliente) <> 0
			THEN 1
			ELSE 0 END) AS BIT) AS TieneDomicilios,
	CAST((CASE WHEN (SELECT COUNT(tc.IdTelefonoCliente) 
					FROM TelefonosClientes tc
					WHERE tc.IdCliente = c.IdCliente) <> 0
			THEN 1
			ELSE 0 END) AS BIT) AS TieneTelefonos,
	CAST((CASE WHEN cd.Observacion <> ''
			THEN 1
			ELSE 0 END) AS BIT) AS TieneObservacion,
	CAST((CASE WHEN cd.Imagen IS NULL
			THEN 0
			ELSE 1 END) AS BIT) AS TieneImagen
	FROM Clientes c
		INNER JOIN ClientesDetalles cd
			ON c.IdCliente = cd.IdCliente
	WHERE c.IdCliente = @IdCliente
	
SELECT ISNULL(ctfp.IdClienteTipoFormaPago, 0) AS IdClienteTipoFormaPago,
	c1.IdCliente,
	tfp.IdTipoFormaPago,
	CAST((CASE WHEN ISNULL(ctfp.IdClienteTipoFormaPago, 0) = 0
			THEN 0
			ELSE 1 END) AS BIT) AS TienePermiso
	FROM Clientes c1
		CROSS JOIN TiposFormasPagos tfp
		INNER JOIN Clientes c2 
			ON c1.IdCliente = c2.IdCliente
		LEFT JOIN ClientesTiposFormasPagos ctfp 
			ON tfp.IdTipoFormaPago = ctfp.IdTipoFormaPago
			AND c1.IdCliente = ctfp.IdCliente
	WHERE c1.IdCliente = @IdCliente